package com.tg.paw.ums.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author ChengJianSheng
 * @date 2020-03-08
 */
public class JWTUtil {

    /**
     * 15天
     */
    public static final long TOKEN_EXPIRE_TIME = 15*24*60*60*1000L;
    /**
     * 16天
     */
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 16*24*60*60*1000L;

    private static final String ISSUER = "paw-patrol";



    /**
     * 生成Token
     * @param username 用户标识（不一定是用户名，有可能是用户ID或者手机号什么的）
     * @param secretKey
     * @return
     */
    public static TokenData generateToken(String username, String secretKey) {
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        Date now = new Date();
        Date expireTime = new Date(now.getTime() + TOKEN_EXPIRE_TIME);
        Date refreshExpireTime = new Date(now.getTime() + REFRESH_TOKEN_EXPIRE_TIME);

        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(now)
                .withExpiresAt(expireTime)
                .withClaim("username", username)
                .sign(algorithm);

        String refreshToken = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(now)
                .withExpiresAt(refreshExpireTime)
                .withClaim("username", username)
                .sign(algorithm);
        long expireIn = expireTime.getTime()-System.currentTimeMillis();
        long refreshExpireIn = refreshExpireTime.getTime()-System.currentTimeMillis();
        TokenData tokenData = new TokenData(TokenData.API_KEY,token,refreshToken,expireIn,refreshExpireIn);

        return tokenData;
    }

    /**
     * 校验Token
     * @param token
     * @param secretKey
     * @return
     */
    public static void verifyToken(String token, String secretKey) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secretKey);
            JWTVerifier jwtVerifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            jwtVerifier.verify(token);
        }catch (Exception ex) {
            throw new RuntimeException("验证jwt token异常");
        }
    }

    /**
     * 从Token中提取用户信息
     * @param token
     * @return
     */
    public static String getUserInfo(String token) {
        DecodedJWT decodedJWT = JWT.decode(token);
        String username = decodedJWT.getClaim("username").asString();
        return username;
    }

}










